package csx.study.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MqConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(messageConverter());

        // Return 回调（交换机->队列失败）
        template.setReturnsCallback(returned -> {
            log.error("消息路由失败 | RK:{} | Ex:{} | Code:{}",
                    returned.getRoutingKey(),
                    returned.getExchange(),
                    returned.getReplyCode());
            log.debug("返回详情: {}", returned);
        });

        // Confirm 回调（生产者->交换机）
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                log.error("消息未到达交换机 | ID:{} | 原因:{}",
                        correlationData != null ? correlationData.getId() : "N/A",
                        cause);
            }else{
                log.debug("消息成功到达交换机 | ID:{}",
                        correlationData != null ? correlationData.getId() : "N/A");
            }
        });

        // 等价于publisher-returns: true
        //template.setMandatory(true);

        //template.setObservationEnabled(true);

        return template;
    }

    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }
}